/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By zhanglin
* 注意：
* 本软件为zhanglin开发研制
 */
package model

import (
	"shop/global"
	"time"
)

type IMenu interface {
	InsertMenu() (int64, error)
	DeleteMenu(id int64) error
	UpdateMenu() error
	FindMenuList() (interface{}, error)
	SplitPageMenuList(pageIndex int64, pageSize int64) (interface{}, error)
}

/**
	Menu实体对象
 **/
type Menu struct {
	Id int64 `json:"id" gorm:"primary_key"` //ID

	IFrame uint `json:"i_frame"` //是否外链

	Name string `json:"name"` //菜单名称

	Component string `json:"component"` //组件

	Pid int64 `json:"pid"` //上级菜单ID

	Sort int64 `json:"sort"` //排序

	Icon string `json:"icon"` //图标

	Path string `json:"path"` //链接地址

	Cache uint `json:"cache"` //缓存

	Hidden uint `json:"hidden"` //是否隐藏

	ComponentName string `json:"component_name"` //组件名称

	CreateTime time.Time `json:"create_time"` //创建日期

	Permission string `json:"permission"` //权限

	Type int32 `json:"type"` //类型
}

func (vo *Menu) InsertMenu() (int64, error) {
	table := global.GDB.Table("menu")
	if err := table.Create(&vo).Error; err != nil {
		return 0, err
	}

	return vo.Id, nil
}

func (vo *Menu) DeleteMenu(id int64) error {
	table := global.GDB.Table("menu")
	table = table.Where("id = ?", id)
	if err := table.Delete(Menu{}).Error; err != nil {
		return err
	}
	return nil
}

func (vo *Menu) UpdateMenu() error {

	table := global.GDB.Table("menu")
	table = table.Where("id = ?", vo.Id)
	if err := table.Updates(map[string]interface{}{
		"id": vo.Id, "i_frame": vo.IFrame, "name": vo.Name, "component": vo.Component, "pid": vo.Pid, "sort": vo.Sort, "icon": vo.Icon, "path": vo.Path, "cache": vo.Cache, "hidden": vo.Hidden, "component_name": vo.ComponentName, "create_time": vo.CreateTime, "permission": vo.Permission, "type": vo.Type}).Error; err != nil {
		return err
	}
	return nil
}

func (vo *Menu) FindMenuList() ([]Menu, error) {
	var lists []Menu
	table := global.GDB.Table("menu")
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}
	return lists, nil
}

func (vo *Menu) SplitPageMenuList(pageIndex int64, pageSize int64) (interface{}, error) {
	var lists []Menu
	var total int64
	table := global.GDB.Table("menu")
	table = table.Select("  id,   i_frame,   name,   component,   pid,   sort,   icon,   path,   cache,   hidden,   component_name,   create_time,   permission,   type   ")
	if err := table.Count(&total).Error; err != nil {
		return lists, err
	}
	table = table.Offset((pageIndex - 1) * pageSize).Limit(pageSize)
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}

	m := make(map[string]interface{})
	m["lists"] = lists
	m["total"] = total
	return m, nil
}
